<template>
  <div>
    <a-button @click="showModal = true">
      {{ text || "上传图片" }}
    </a-button>

    <a-modal
      v-if="showModal"
      v-model:open="showModal"
      title="图片素材库"
      ok-text="确认"
      cancel-text="取消"
      :width="820"
      :maskClosable="false"
      :closable="false"
      @ok="handleOk"
      @cancel="() => (showModal = false)"
    >
      <a-row style="width: 752px; min-height: 520px; margin-top: 24px">
        <!-- 左侧分类 -->
        <a-col :span="7">
          <TreeCategory
            :selected="category_ids"
            type="no-cate"
            text="图片"
            @update="onUpdateCategory"
          />
        </a-col>

        <!-- 右侧内容 -->
        <a-col :span="17">
          <a-row style="margin-bottom: 24px; padding-left: 10px">
            <a-col :span="24">
              <UploadImageSub
                :categoryIds="category_ids"
                @update="resetImageList"
              />
            </a-col>
          </a-row>

          <a-col v-if="imageList.length === 0" :span="24">
            <a-empty description="暂无图片" />
          </a-col>

          <!-- 图片列表 -->
          <div class="image-list-box">
            <div
              v-for="item in imageList"
              :key="item.id"
              class="image-item"
              :style="{ backgroundImage: `url(${resourceUrl[item.id]})` }"
              @click="handleSelect(item)"
            >
              <i
                v-if="selected === resourceUrl[item.id]"
                class="checked"
                @click.stop="cancelSelect"
              >
                <CheckOutlined />
              </i>
            </div>
          </div>

          <!-- 分页 -->
          <a-col
            v-if="imageList.length > 0"
            :span="24"
            style="display: flex; flex-direction: row-reverse"
          >
            <a-pagination
              show-size-changer
              :total="total"
              :current="page"
              :pageSize="size"
              @change="onPageChange"
            />
          </a-col>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { message } from "ant-design-vue";
import { CheckOutlined } from "@ant-design/icons-vue";
import { resource } from "@/api";
import UploadImageSub from "./upload-image-sub.vue";
import TreeCategory from "./tree-category.vue";

interface Option {
  id: string | number;
  name: string;
  children?: Option[];
}

interface ImageItem {
  id: number;
  category_id: number;
  name: string;
  extension: string;
  size: number;
  disk: string;
  file_id: string;
  path: string;
  url: string;
  created_at: string;
}

interface PropsInterface {
  text?: string;
  onSelected: (url: string, id: number) => void;
}

const props = defineProps<PropsInterface>();

const showModal = ref(false);
const category_ids = ref<any[]>([]);

const imageList = ref<ImageItem[]>([]);
const refresh = ref(false);
const page = ref(1);
const size = ref(15);
const total = ref(0);
const selected = ref<string>("");
const selectedKey = ref<number>(0);
const resourceUrl = ref<Record<number, string>>({});

// 获取图片列表
const getImageList = () => {
  let categoryIds = category_ids.value.join(",");
  resource
    .resourceList(page.value, size.value, "", "", "", "IMAGE", categoryIds)
    .then((res: any) => {
      total.value = res.data.result.total;
      imageList.value = res.data.result.data;
      resourceUrl.value = res.data.resource_url;
    })
    .catch((err: any) => {
      console.error("错误,", err);
    });
};

// 重置列表
const resetImageList = () => {
  page.value = 1;
  imageList.value = [];
  refresh.value = !refresh.value;
};

// 监听弹窗/筛选条件，加载图片
watch([category_ids, refresh, page, size, showModal], ([, , , , modal]) => {
  if (modal) {
    getImageList();
  }
});

// 选择图片
const handleSelect = (item: ImageItem) => {
  selected.value = resourceUrl.value[item.id];
  selectedKey.value = item.id;
};

// 取消选择
const cancelSelect = () => {
  selected.value = "";
  selectedKey.value = 0;
};

// 分类更新
const onUpdateCategory = (keys: any) => {
  selected.value = "";
  category_ids.value = keys;
};

// 确认按钮
const handleOk = () => {
  if (!selected.value) {
    message.error("请选择图片后确定");
    return;
  }
  props.onSelected(selected.value, selectedKey.value);
  showModal.value = false;
};

// 分页事件
const onPageChange = (currentPage: number, currentSize: number) => {
  page.value = currentPage;
  size.value = currentSize;
};
</script>

<style scoped lang="less">
.categoryItem {
  width: 100%;
  height: 50px;
  line-height: 50px;
  float: left;
  cursor: pointer;
  display: flex;

  &.active {
    background-color: red;
    color: white;
  }
}

.categoryTitle {
  width: 100%;
  height: 30px;
  line-height: 30px;
  display: flex;
}

.checked {
  width: 16px;
  height: 16px;
  background: #ff4d4f;
  border-radius: 3px;
  border: 2px solid #ff4d4f;
  position: absolute;
  left: 5px;
  top: 5px;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  cursor: pointer;
}
</style>
